/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.edu.sd.jxta;

import java.io.File;
import net.jxta.discovery.DiscoveryService;
import net.jxta.peer.PeerID;
import net.jxta.peergroup.PeerGroup;
import net.jxta.pipe.PipeService;
import net.jxta.platform.NetworkManager;
import net.jxta.protocol.PeerGroupAdvertisement;

/**
 *
 * @author SD
 */
public class JXTAManager {

    private boolean initialized = false;
    private static JXTAManager instance = new JXTAManager();
    private PeerGroup netPeerGroup = null;
    private PeerGroupAdvertisement groupAdvertisement = null;
    private DiscoveryService discovery;
    private PipeService pipeService;
    private NetworkManager manager;

    private JXTAManager() {
        System.setProperty("net.jxta.logging.Logging", "SEVERE");
        System.setProperty("net.jxta.level", "SEVERE");
    }

    public static JXTAManager getInstance() {
        return instance;
    }

    public DiscoveryService getDiscovery() {
        validateInitialized();
        return discovery;
    }

    public PeerGroup getNetPeerGroup() {
        validateInitialized();
        return netPeerGroup;
    }

    public PipeService getPipeService() {
        validateInitialized();
        return pipeService;
    }

    public PeerGroupAdvertisement getGroupAdvertisement() {
        validateInitialized();
        return groupAdvertisement;
    }

    public PeerID getPeerID() {
        validateInitialized();
        return manager.getPeerID();
    }

    public void validateInitialized() {
        if (initialized == false) {
            throw new RuntimeException("JXTA IS NOT INITIALIZED YOU MUST FIRST RUN: JXTAManager.getInstance().startJXTA();");
        }
    }

    public void startJXTA() {

        try {
            manager = new NetworkManager(NetworkManager.ConfigMode.ADHOC, "MultiServicePeer",
                    new File(new File(".cache"), "MultiServicePeer").toURI());
            manager.startNetwork();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }

        netPeerGroup = manager.getNetPeerGroup();
        groupAdvertisement = netPeerGroup.getPeerGroupAdvertisement();
        discovery = netPeerGroup.getDiscoveryService();
        pipeService = netPeerGroup.getPipeService();
        initialized = true;
    }

    public void stopJXTA() {
        manager.stopNetwork();
        initialized = false;
    }
}
